# -*- coding: utf-8 -*-

from model.gamestate import *
import json
import urllib2
import urllib
from constants import JSON_TIMEOUT
from kivy.network.urlrequest import UrlRequest


class JsonRoundsCreater():
    def dump_to_url(self, url, json_string):
        try:
            req = UrlRequest(url, req_body=
                             urllib.urlencode([("history", json_string)]))
        except:
            pass

    def create_json_rounds(self, rounds, hat, settings,
                           remote_id, strategy, pin):
        all_json = {
            u'rounds': [],
            u'settings': {
                u'skip_words_per_round': settings.skip_words,
                u'time_before_out_sec': settings.time_before_out_sec,
                u'time_per_round_sec': settings.time_per_round_sec
            },
            u'is_paired_strategy': strategy.is_pair_strategy(),
            u'words_in_hat': []
        }

        if pin is not None:
            all_json[u'pin'] = pin

        if remote_id is not None:
            all_json[u'remote_id'] = remote_id

        for word in hat.words:
            owner_name = None
            if word.owner is not None:
                owner_name = word.owner.name
            all_json[u'words_in_hat'].append({u'text': word.text,
                                              u'owner': owner_name})

        for game_round in rounds:
            json_round = {
                u'words': [],
                u'player1': game_round.players_pair[0].name,
                u'player2': game_round.players_pair[1].name
            }
            for word in game_round.words:
                owner_name = None
                if word.word.owner is not None:
                    owner_name = word.word.owner.name
                wgs = {
                    u'text': word.word.text,
                    u'owner': owner_name,
                    u'result': WordGuessResult.text_repr[word.result],
                    u'time': word.time
                }
                json_round[u'words'].append(wgs)
            all_json[u'rounds'].append(json_round)
        return json.dumps(all_json, encoding='utf-8', sort_keys=True)
